#pragma once
#include <string>
#include <vector>
#include <memory>

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "example/stb_image.h"
#include "example/stb_image_write.h"

class ImageCompress
{
public:
    // 压缩图片,quality范围1-100,1为最低质量,100为最高质量
    static bool compress(const std::string &input_path, const std::string &output_path, int quality)
    {
        int width, height, channels;
        unsigned char *image_data = stbi_load(input_path.c_str(), &width, &height, &channels, 0);
        if (!image_data)
        {
            return false;
        }

        bool success = false;
        std::string ext = get_file_extension(output_path);

        if (ext == "jpg" || ext == "jpeg")
        {
            success = stbi_write_jpg(output_path.c_str(), width, height, channels, image_data, quality);
        }
        else if (ext == "png")
        {
            // PNG使用zlib压缩,quality范围1-10
            int png_quality = quality / 10;
            if (png_quality < 1)
                png_quality = 1;
            success = stbi_write_png(output_path.c_str(), width, height, channels, image_data, width * channels);
        }
        else if (ext == "bmp")
        {
            success = stbi_write_bmp(output_path.c_str(), width, height, channels, image_data);
        }
        else if (ext == "tga")
        {
            success = stbi_write_tga(output_path.c_str(), width, height, channels, image_data);
        }

        stbi_image_free(image_data);
        return success;
    }

private:
    static std::string get_file_extension(const std::string &path)
    {
        size_t dot_pos = path.find_last_of(".");
        if (dot_pos != std::string::npos)
        {
            std::string ext = path.substr(dot_pos + 1);
            // 转换为小写
            for (char &c : ext)
            {
                c = std::tolower(c);
            }
            return ext;
        }
        return "";
    }
};